package com.outsourcing.bottle.ui;

import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.CompanyEntry;
import com.outsourcing.bottle.domain.CompanyInfo;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class SettingCompanyActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private EditText editView;
	private ImageView addView;
	private ListView listView;
	
	private final int init_company_info = 1;
	private final int error = 2;
	private final int add_company = 3;
	private final int delete_company = 4;
	
	private Handler handler;
	private List<CompanyEntry> companyList;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.setting_company);
		handler = new Handler(this);
		initWidget();
		UICore.eventTask(this, this, init_company_info, "init_company_info", null);
	}
	
	private void initWidget() {
		editView = (EditText) findViewById(R.id.setting_company_edit);
		editView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					if (editView.getText().toString().trim().equals("")) {
						onToast(getString(R.string.setting_company_error_tips));
						return true;
					}
					UICore.eventTask(SettingCompanyActivity.this, SettingCompanyActivity.this, add_company, "add_company", null);
				}
				return false;
			}
		});
		addView = (ImageView) findViewById(R.id.setting_company_add);
		addView.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.setting_company_list);
	}
	
	@Override
	public void onClick(View v) {
		if (v == addView) {
			if (editView.getText().toString().trim().equals("")) {
				onToast(getString(R.string.setting_company_error_tips));
				return;
			}
			UICore.eventTask(this, this, add_company, "add_company", null);
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case init_company_info:
			if (companyList != null && !companyList.isEmpty()) {
				CompanyAdapter adapter = new CompanyAdapter();
				listView.setAdapter(adapter);
			}
			break;
		case error:
			onToast((String) msg.obj);
			break;
		case delete_company:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_company_info, "init_company_info", null);
			break;
		case add_company:
			onToast((String) msg.obj);
			UICore.eventTask(this, this, init_company_info, "init_company_info", null);
			break;
		default:
			break;
		}
		return false;
	}
	
	public void back(View v) {
		finish();
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_company_info:
			initCompanyInfo();
			break;
		case delete_company:
			deleteCompany((String) obj);
			break;
		case add_company:
			addCompany();
			break;
		default:
			break;
		}
	}
	
	private void initCompanyInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_work_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		try {
			String result = HttpUtils.doGet(url.toString());
			if (result != null) {
				Gson gson = new Gson();
				CompanyInfo info = gson.fromJson(result, CompanyInfo.class);
				if (info.getResults().getAuthok() == 0) {
					Message msg = Message.obtain(handler, error, info.getResults().getErrmsg());
					handler.sendMessage(msg);
				} else {
					companyList = info.getMycompanies_list();
					handler.sendEmptyMessage(init_company_info);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void deleteCompany(String companyid) {
		String url = UrlConfig.delete_company_info;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("companyid", companyid);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		getLoginUserInfo();
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, delete_company, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void addCompany() {
		String url = UrlConfig.add_company_info;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("company", editView.getText().toString().trim());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int success = resultObj.getInt("success");
	        	if (success == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		getLoginUserInfo();
	        		String successmsg = resultObj.getString("successmsg");
					Message msg = Message.obtain(handler, add_company, successmsg);
					handler.sendMessage(msg);
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			if (loginUserInfo.getResults().getAuthok() == 1) {
				LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
				if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
					loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				} else {
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class CompanyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return companyList.size();
		}

		@Override
		public Object getItem(int position) {
			return companyList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.setting_listitem, null);
			}
			TextView company = (TextView) convertView.findViewById(R.id.setting_listitem_name);
			ImageView add = (ImageView) convertView.findViewById(R.id.setting_listitem_image);
			final CompanyEntry entry = companyList.get(position);
			if (entry != null) {
				company.setText(entry.getCompany());
				add.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int companyid = entry.getCompanyid();
						UICore.eventTask(SettingCompanyActivity.this,
								SettingCompanyActivity.this, delete_company, "delete_company", String.valueOf(companyid));
					}
				});
			}
			return convertView;
		}
		
	}
}
